const router = require("express-promise-router")();
const express = require('express');
const UserEnhanced = require("../services/user_enhanced");
const MaterialEnhanced = require("../services/material_enhanced");
const CabinetEnhanced = require("../services/cabinet_enhanced");
const WhitelistEnhanced = require("../services/whitelist_enhanced");
const ApplicationService = require("../services/application");
const DeviceService = require("../services/device");
const {checkTeacherOrAdmin} = require("../auth_checker");
const ws=require("../websocket");
const CabinetService=require("../services/cabinet");
// 用户管理相关API
/**
 * @openapi
 * /api/v2/users:
 *   get:
 *     tags:
 *     - user
 *     summary: 获取用户列表
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: 页码
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *         description: 每页数量
 *       - in: query
 *         name: search
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: role
 *         schema:
 *           type: string
 *         description: 角色筛选
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *         description: 状态筛选
 *     responses:
 *       200:
 *         description: 成功返回用户列表
 */
router.get('/users', checkTeacherOrAdmin, async (req, res) => {
    try {
        const options = {
            page: parseInt(req.query.page) || 1,
            pageSize: parseInt(req.query.pageSize) || 10,
            search: req.query.search || '',
            role: req.query.role || '',
            status: req.query.status || ''
        };
        
        const result = await UserEnhanced.getUserList(options);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/users:
 *   post:
 *     tags:
 *     - user
 *     summary: 创建用户
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *               password:
 *                 type: string
 *               email:
 *                 type: string
 *               role:
 *                 type: string
 *               name:
 *                 type: string
 *               phone:
 *                 type: string
 *               status:
 *                 type: string
 *       required: true
 *     responses:
 *       201:
 *         description: 创建成功
 *       400:
 *         description: 创建失败
 */
router.post('/users', checkTeacherOrAdmin, async (req, res) => {
    try {
        const userData = req.body;
        const result = await UserEnhanced.createUser(userData);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/users/{id}:
 *   put:
 *     tags:
 *     - user
 *     summary: 更新用户
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 用户ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *     responses:
 *       200:
 *         description: 更新成功
 *       404:
 *         description: 用户不存在
 */
router.put('/users/:id', checkTeacherOrAdmin, async (req, res) => {
    try {
        const userId = req.params.id;
        const updateData = req.body;
        const result = await UserEnhanced.updateUser(userId, updateData);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/users/{id}:
 *   delete:
 *     tags:
 *     - user
 *     summary: 删除用户
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 用户ID
 *     responses:
 *       200:
 *         description: 删除成功
 *       404:
 *         description: 用户不存在
 */
router.delete('/users/:id', checkTeacherOrAdmin, async (req, res) => {
    try {
        const userId = req.params.id;
        const result = await UserEnhanced.deleteUser(userId);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/users/batch:
 *   post:
 *     tags:
 *     - user
 *     summary: 批量操作用户
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               action:
 *                 type: string
 *                 enum: [delete, activate, deactivate, resetPassword]
 *               userIds:
 *                 type: array
 *                 items:
 *                   type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 批量操作成功
 */
router.post('/users/batch', checkTeacherOrAdmin, async (req, res) => {
    try {
        const { action, userIds } = req.body;
        const result = await UserEnhanced.batchOperation(action, userIds);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/users/import:
 *   post:
 *     tags:
 *     - user
 *     summary: 导入用户
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               users:
 *                 type: array
 *                 items:
 *                   type: object
 *       required: true
 *     responses:
 *       200:
 *         description: 导入成功
 */
router.post('/users/import', checkTeacherOrAdmin, async (req, res) => {
    try {
        const { users } = req.body;
        const result = await UserEnhanced.importUsers(users);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/users/export:
 *   get:
 *     tags:
 *     - user
 *     summary: 导出用户
 *     responses:
 *       200:
 *         description: 导出成功
 */
router.get('/users/export', checkTeacherOrAdmin, async (req, res) => {
    try {
        const result = await UserEnhanced.exportUsers();
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/users/stats:
 *   get:
 *     tags:
 *     - user
 *     summary: 获取用户统计
 *     responses:
 *       200:
 *         description: 统计数据
 */
router.get('/users/stats', checkTeacherOrAdmin, async (req, res) => {
    try {
        const result = await UserEnhanced.getUserStats();
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 物料管理相关API
/**
 * @openapi
 * /api/v2/materials:
 *   get:
 *     tags:
 *     - material
 *     summary: 获取物料列表
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: 页码
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *         description: 每页数量
 *       - in: query
 *         name: search
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: category
 *         schema:
 *           type: string
 *         description: 类别筛选
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *         description: 状态筛选
 *     responses:
 *       200:
 *         description: 成功返回物料列表
 */
router.get('/materials', async (req, res) => {
    try {
        const options = {
            page: parseInt(req.query.page) || 1,
            pageSize: parseInt(req.query.pageSize) || 10,
            search: req.query.search || '',
            category: req.query.category || '',
            status: req.query.status || ''
        };
        
        const result = await MaterialEnhanced.getMaterials(options);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/materials:
 *   post:
 *     tags:
 *     - material
 *     summary: 创建物料
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               category:
 *                 type: string
 *               description:
 *                 type: string
 *               stock:
 *                 type: integer
 *               unit:
 *                 type: string
 *               price:
 *                 type: number
 *               hasBarcode:
 *                 type: boolean
 *               barcode:
 *                 type: string
 *               status:
 *                 type: string
 *       required: true
 *     responses:
 *       201:
 *         description: 创建成功
 *       400:
 *         description: 创建失败
 */
router.post('/materials', checkTeacherOrAdmin, async (req, res) => {
    try {
        const materialData = req.body;
        const result = await MaterialEnhanced.createMaterial(materialData);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/materials/{id}:
 *   put:
 *     tags:
 *     - material
 *     summary: 更新物料
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *     responses:
 *       200:
 *         description: 更新成功
 *       404:
 *         description: 物料不存在
 */
router.put('/materials/:id', checkTeacherOrAdmin, async (req, res) => {
    try {
        const materialId = req.params.id;
        const updateData = req.body;
        const result = await MaterialEnhanced.updateMaterial(materialId, updateData);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/materials/{id}:
 *   delete:
 *     tags:
 *     - material
 *     summary: 删除物料
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料ID
 *     responses:
 *       200:
 *         description: 删除成功
 *       404:
 *         description: 物料不存在
 */
router.delete('/materials/:id', checkTeacherOrAdmin, async (req, res) => {
    try {
        const materialId = req.params.id;
        const result = await MaterialEnhanced.deleteMaterial(materialId);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/materials/categories:
 *   get:
 *     tags:
 *     - material
 *     summary: 获取物料类别
 *     responses:
 *       200:
 *         description: 成功返回类别列表
 */
router.get('/materials/categories', async (req, res) => {
    try {
        const result = await MaterialEnhanced.getCategories();
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/materials/batch:
 *   post:
 *     tags:
 *     - material
 *     summary: 批量操作物料
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               action:
 *                 type: string
 *                 enum: [delete, activate, deactivate, updateStock]
 *               materialIds:
 *                 type: array
 *                 items:
 *                   type: string
 *               data:
 *                 type: object
 *       required: true
 *     responses:
 *       200:
 *         description: 批量操作成功
 */
router.post('/materials/batch', checkTeacherOrAdmin, async (req, res) => {
    try {
        const { action, materialIds, data } = req.body;
        const result = await MaterialEnhanced.batchOperation(action, materialIds, data);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/materials/import:
 *   post:
 *     tags:
 *     - material
 *     summary: 导入物料
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               materials:
 *                 type: array
 *                 items:
 *                   type: object
 *       required: true
 *     responses:
 *       200:
 *         description: 导入成功
 */
router.post('/materials/import', checkTeacherOrAdmin, async (req, res) => {
    try {
        const { materials } = req.body;
        const result = await MaterialEnhanced.importMaterials(materials);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/materials/export:
 *   get:
 *     tags:
 *     - material
 *     summary: 导出物料
 *     responses:
 *       200:
 *         description: 导出成功
 */
router.get('/materials/export', checkTeacherOrAdmin, async (req, res) => {
    try {
        const result = await MaterialEnhanced.exportMaterials();
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/materials/stats:
 *   get:
 *     tags:
 *     - material
 *     summary: 获取物料统计
 *     responses:
 *       200:
 *         description: 统计数据
 */
router.get('/materials/stats', checkTeacherOrAdmin, async (req, res) => {
    try {
        const result = await MaterialEnhanced.getMaterialStats();
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 物料柜管理相关API
/**
 * @openapi
 * /api/v2/cabinets_list:
 *   get:
 *     tags:
 *     - cabinet
 *     summary: 获取物料柜列表
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: 页码
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *         description: 每页数量
 *       - in: query
 *         name: search
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *         description: 状态筛选
 *     responses:
 *       200:
 *         description: 成功返回物料柜列表
 */
router.post('/cabinets_list', checkTeacherOrAdmin, async (req, res) => {
    console.log('获取物料柜列表', req.body);

    try {
        const options = {
            page: parseInt(req.body.page) || 1,
            pageSize: parseInt(req.body.pageSize) || 10,
            search: req.body.search || '',
            status: req.body.status || ''
        };
        
        const result = await CabinetEnhanced.getCabinetList(options);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets:
 *   post:
 *     tags:
 *     - cabinet
 *     summary: 创建物料柜
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               location:
 *                 type: string
 *               description:
 *                 type: string
 *               totalSlots:
 *                 type: integer
 *               slotConfig:
 *                 type: object
 *               status:
 *                 type: string
 *       required: true
 *     responses:
 *       201:
 *         description: 创建成功
 *       400:
 *         description: 创建失败
 */
router.post('/cabinets', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetData = req.body;
        const result = await CabinetEnhanced.createCabinet(cabinetData);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinet_update/{id}:
 *   put:
 *     tags:
 *     - cabinet
 *     summary: 更新物料柜
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *     responses:
 *       200:
 *         description: 更新成功
 *       404:
 *         description: 物料柜不存在
 */
router.put('/cabinet_update/:id', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const updateData = req.body;
        const result = await CabinetEnhanced.updateCabinet(cabinetId, updateData);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinet_remove/{id}:
 *   post:
 *     tags:
 *     - cabinet
 *     summary: 删除物料柜
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *     responses:
 *       200:
 *         description: 删除成功
 *       404:
 *         description: 物料柜不存在
 */
router.post('/cabinet_remove/:id', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const result = await CabinetEnhanced.deleteCabinet(cabinetId);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets/{id}:
 *   get:
 *     tags:
 *     - cabinet
 *     summary: 获取物料柜信息
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *     responses:
 *       200:
 *         description: 成功返回物料柜信息
 *       404:
 *         description: 物料柜不存在
 */
router.get('/cabinets/:id', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const result = await CabinetEnhanced.getCabinetById(cabinetId);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets/{id}/slots:
 *   get:
 *     tags:
 *     - cabinet
 *     summary: 获取物料柜格子列表
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *     responses:
 *       200:
 *         description: 成功返回格子列表
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 slots:
 *                   type: array
 *                   items:
 *                     type: object
 *                     properties:
 *                       id:
 *                         type: string
 *                       cellNumber:
 *                         type: integer
 *                       boardNumber:
 *                         type: integer
 *                       position:
 *                         type: integer
 *                       size:
 *                         type: string
 *                       status:
 *                         type: string
 *                       isEnabled:
 *                         type: boolean
 *                       material:
 *                         type: object
 *                       quantity:
 *                         type: integer
 *                       description:
 *                         type: string
 *       400:
 *         description: 获取失败
 */
router.get('/cabinets/:id/slots', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const result = await CabinetEnhanced.getCabinetSlots(cabinetId);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets/{id}/slots:
 *   post:
 *     tags:
 *     - cabinet
 *     summary: 创建格子
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               cellNumber:
 *                 type: integer
 *               boardNumber:
 *                 type: integer
 *               size:
 *                 type: string
 *               position:
 *                 type: string
 *               status:
 *                 type: string
 *               isEnabled:
 *                 type: boolean
 *               description:
 *                 type: string
 *       required: true
 *     responses:
 *       201:
 *         description: 创建成功
 *       400:
 *         description: 创建失败
 */
router.post('/cabinets/:id/slots', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const slotData = req.body;
        const result = await CabinetEnhanced.createSlot(cabinetId, slotData);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets/{id}/slots/{slotId}:
 *   put:
 *     tags:
 *     - cabinet
 *     summary: 更新格子信息
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *       - in: path
 *         name: slotId
 *         required: true
 *         schema:
 *           type: string
 *         description: 格子ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               cellNumber:
 *                 type: integer
 *               boardNumber:
 *                 type: integer
 *               size:
 *                 type: string
 *               position:
 *                 type: integer
 *               status:
 *                 type: string
 *               isEnabled:
 *                 type: boolean
 *               description:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 更新成功
 *       400:
 *         description: 更新失败
 *       404:
 *         description: 格子不存在
 */
router.put('/cabinets/:id/slots/:slotId', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const slotId = req.params.slotId;
        const updateData = req.body;
        const result = await CabinetEnhanced.updateSlot(cabinetId, slotId, updateData);
        if (result.success) {
            res.json(result);
        } else {
            res.status(404).json(result);
        }
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets/{id}/slots/batch:
 *   post:
 *     tags:
 *     - cabinet
 *     summary: 批量创建格子
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               boardCount:
 *                 type: integer
 *                 description: 控制板数量
 *               startBoardNumber:
 *                 type: integer
 *                 description: 起始控制板编号
 *                 default: 1
 *               cellsPerBoard:
 *                 type: integer
 *                 description: 每块控制板的格子数量
 *               defaultSize:
 *                 type: string
 *                 description: 默认格子大小
 *                 enum: [small, medium, large]
 *               startNumber:
 *                 type: integer
 *                 description: 起始格子编号
 *       required: true
 *     responses:
 *       201:
 *         description: 批量创建成功
 *       400:
 *         description: 批量创建失败
 */
router.post('/cabinets/:id/slots/batch', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const config = req.body;
        const result = await CabinetEnhanced.batchCreateSlots(cabinetId, config);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets/{id}/slots/batch:
 *   delete:
 *     tags:
 *     - cabinet
 *     summary: 批量删除格子
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               slotIds:
 *                 type: array
 *                 items:
 *                   type: string
 *                 description: 要删除的格子ID数组
 *       required: true
 *     responses:
 *       200:
 *         description: 批量删除成功
 *       400:
 *         description: 批量删除失败
 */
router.delete('/cabinets/:id/slots/batch', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const { slotIds } = req.body;
        const result = await CabinetEnhanced.batchDeleteSlots(cabinetId, slotIds);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets/{id}/slots/{slotId}:
 *   delete:
 *     tags:
 *     - cabinet
 *     summary: 删除格子
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *       - in: path
 *         name: slotId
 *         required: true
 *         schema:
 *           type: string
 *         description: 格子ID
 *     responses:
 *       200:
 *         description: 删除成功
 *       404:
 *         description: 格子不存在
 */
router.delete('/cabinets/:id/slots/:slotId', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const slotId = req.params.slotId;
        const result = await CabinetEnhanced.deleteSlot(cabinetId, slotId);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets/{id}/slots/{slotId}/{action}:
 *   post:
 *     tags:
 *     - cabinet
 *     summary: 开启/关闭格子门
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *       - in: path
 *         name: slotId
 *         required: true
 *         schema:
 *           type: string
 *         description: 格子ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               reason:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 开门成功
 *       400:
 *         description: 开门失败
 */
router.post('/cabinets/:id/slots/:gridId/:action', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        const cabinetData = await CabinetEnhanced.getCabinetById(cabinetId);
        const cabinet = cabinetData.cabinet;
        const gridId = req.params.gridId;
        const status = req.params.action; // open or close
        const grid=await CabinetEnhanced.getGridById(gridId);
       const data = {
                            type: status,
                            lockerid: cabinet.HID,
                            boardid: Number(grid.cid),
                            portid: Number(grid.boardNumber),
                            cmd: "server"
                        };
          ws.send(JSON.stringify(data));  
          //添加开柜子日志
          const username=req.session.user.username;
           await CabinetService.saveCabinetLog(cabinet.HID,grid.number,username,"open")
       
        const result = {
            success: true,
            message: '格子门已开启',
            data
        };
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets/{id}/status:
 *   get:
 *     tags:
 *     - cabinet
 *     summary: 获取物料柜状态
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 物料柜ID
 *     responses:
 *       200:
 *         description: 成功返回物料柜状态
 */
router.get('/cabinets/:id/status', checkTeacherOrAdmin, async (req, res) => {
    try {
        const cabinetId = req.params.id;
        
        // 这里应该调用硬件接口获取实时状态
        // 现在先模拟返回数据
        const result = {
            success: true,
            data: {
                cabinetId,
                status: 'online',
                timestamp: new Date()
            }
        };
        
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/whitelists:
 *   get:
 *     tags:
 *     - whitelist
 *     summary: 获取白名单列表
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: 页码
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *         description: 每页数量
 *       - in: query
 *         name: search
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *         description: 状态筛选
 *     responses:
 *       200:
 *         description: 成功返回白名单列表
 */
router.post('/whitelists_info', checkTeacherOrAdmin, async (req, res) => {
    try {
        const options = {
            page: parseInt(req.query.page) || 1,
            pageSize: parseInt(req.query.pageSize) || 10,
            search: req.query.search || '',
            status: req.query.status || ''
        };
        console.log('获取白名单列表', options);
        const result = await WhitelistEnhanced.getWhitelists(options);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/whitelists:
 *   post:
 *     tags:
 *     - whitelist
 *     summary: 创建白名单
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               description:
 *                 type: string
 *               managerId:
 *                 type: string
 *               members:
 *                 type: array
 *                 items:
 *                   type: string
 *               allowedMaterials:
 *                 type: array
 *                 items:
 *                   type: string
 *               status:
 *                 type: string
 *       required: true
 *     responses:
 *       201:
 *         description: 创建成功
 *       400:
 *         description: 创建失败
 */
router.post('/whitelists', checkTeacherOrAdmin, async (req, res) => {
    try {
        const whitelistData = req.body;
        const result = await WhitelistEnhanced.createWhitelist(whitelistData);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/whitelists/{id}:
 *   put:
 *     tags:
 *     - whitelist
 *     summary: 更新白名单
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 白名单ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *     responses:
 *       200:
 *         description: 更新成功
 *       404:
 *         description: 白名单不存在
 */
router.put('/whitelists/:id', checkTeacherOrAdmin, async (req, res) => {
    try {
        const whitelistId = req.params.id;
        const updateData = req.body;
        const result = await WhitelistEnhanced.updateWhitelist(whitelistId, updateData);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/whitelists/{id}:
 *   delete:
 *     tags:
 *     - whitelist
 *     summary: 删除白名单
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 白名单ID
 *     responses:
 *       200:
 *         description: 删除成功
 *       404:
 *         description: 白名单不存在
 */
router.delete('/whitelists/:id', checkTeacherOrAdmin, async (req, res) => {
    try {
        const whitelistId = req.params.id;
        const result = await WhitelistEnhanced.deleteWhitelist(whitelistId);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/whitelists/{id}/members:
 *   post:
 *     tags:
 *     - whitelist
 *     summary: 添加白名单成员
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 白名单ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               userIds:
 *                 type: array
 *                 items:
 *                   type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 添加成功
 */
router.post('/whitelists/:id/members', checkTeacherOrAdmin, async (req, res) => {
    try {
        const whitelistId = req.params.id;
        const { userIds } = req.body;
        const result = await WhitelistEnhanced.addMembers(whitelistId, userIds);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/whitelists/{id}/members:
 *   delete:
 *     tags:
 *     - whitelist
 *     summary: 移除白名单成员
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 白名单ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               userIds:
 *                 type: array
 *                 items:
 *                   type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 移除成功
 */
router.delete('/whitelists/:id/members', checkTeacherOrAdmin, async (req, res) => {
    try {
        const whitelistId = req.params.id;
        const { userIds } = req.body;
        const result = await WhitelistEnhanced.removeMembers(whitelistId, userIds);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 申请管理相关API
/**
 * @openapi
 * /api/v2/applications:
 *   get:
 *     tags:
 *     - application
 *     summary: 获取申请列表
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: 页码
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *         description: 每页数量
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *         description: 状态筛选
 *       - in: query
 *         name: userId
 *         schema:
 *           type: string
 *         description: 用户ID筛选
 *       - in: query
 *         name: startDate
 *         schema:
 *           type: string
 *         description: 开始日期
 *       - in: query
 *         name: endDate
 *         schema:
 *           type: string
 *         description: 结束日期
 *     responses:
 *       200:
 *         description: 成功返回申请列表
 */
router.get('/applications', async (req, res) => {
    try {
        const options = {
            page: parseInt(req.query.page) || 1,
            pageSize: parseInt(req.query.pageSize) || 10,
            status: req.query.status || '',
            userId: req.query.userId || '',
            startDate: req.query.startDate || '',
            endDate: req.query.endDate || ''
        };
        
        const result = await ApplicationService.getApplications(options);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/applications:
 *   post:
 *     tags:
 *     - application
 *     summary: 创建申请
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               userId:
 *                 type: string
 *               items:
 *                 type: array
 *                 items:
 *                   type: object
 *                   properties:
 *                     materialId:
 *                       type: string
 *                     quantity:
 *                       type: integer
 *               purpose:
 *                 type: string
 *               expectedReturnDate:
 *                 type: string
 *       required: true
 *     responses:
 *       201:
 *         description: 创建成功
 *       400:
 *         description: 创建失败
 */
router.post('/applications', async (req, res) => {
    try {
        const applicationData = req.body;
        const result = await ApplicationService.createApplication(applicationData);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/applications/{id}/approve:
 *   post:
 *     tags:
 *     - application
 *     summary: 审批申请
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 申请ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               action:
 *                 type: string
 *                 enum: [approve, reject]
 *               reviewerId:
 *                 type: string
 *               reviewNote:
 *                 type: string
 *               items:
 *                 type: array
 *                 items:
 *                   type: object
 *       required: true
 *     responses:
 *       200:
 *         description: 审批成功
 */
router.post('/applications/:id/approve', checkTeacherOrAdmin, async (req, res) => {
    try {
        const applicationId = req.params.id;
        const { action, reviewerId, reviewNote, items } = req.body;
        const result = await ApplicationService.approveApplication(applicationId, {
            action,
            reviewerId,
            reviewNote,
            items
        });
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/applications/batch-approve:
 *   post:
 *     tags:
 *     - application
 *     summary: 批量审批申请
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               applicationIds:
 *                 type: array
 *                 items:
 *                   type: string
 *               action:
 *                 type: string
 *                 enum: [approve, reject]
 *               reviewerId:
 *                 type: string
 *               reviewNote:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 批量审批成功
 */
router.post('/applications/batch-approve', checkTeacherOrAdmin, async (req, res) => {
    try {
        const { applicationIds, action, reviewerId, reviewNote } = req.body;
        const result = await ApplicationService.batchApprove(applicationIds, {
            action,
            reviewerId,
            reviewNote
        });
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/applications/{id}/return:
 *   post:
 *     tags:
 *     - application
 *     summary: 归还物料
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 申请ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               items:
 *                 type: array
 *                 items:
 *                   type: object
 *                   properties:
 *                     materialId:
 *                       type: string
 *                     quantity:
 *                       type: integer
 *                     condition:
 *                       type: string
 *               note:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 归还成功
 */
router.post('/applications/:id/return', checkTeacherOrAdmin, async (req, res) => {
    try {
        const applicationId = req.params.id;
        const { items, note } = req.body;
        const result = await ApplicationService.returnMaterials(applicationId, items, note);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/dashboard/stats:
 *   get:
 *     tags:
 *     - dashboard
 *     summary: 获取仪表板统计数据
 *     responses:
 *       200:
 *         description: 成功返回统计数据
 */
router.get('/dashboard/stats', checkTeacherOrAdmin, async (req, res) => {
    try {
        const userStats = await UserEnhanced.getUserStats();
        const materialStats = await MaterialEnhanced.getMaterialStats();
        const applicationStats = await ApplicationService.getApplicationStats();
        const deviceStats = await DeviceService.getDeviceStats();
        
        res.json({
            users: userStats,
            materials: materialStats,
            applications: applicationStats,
            devices: deviceStats
        });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 设备管理相关API
/**
 * @openapi
 * /api/v2/devices:
 *   get:
 *     tags:
 *     - device
 *     summary: 获取设备列表
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: 页码
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *         description: 每页数量
 *       - in: query
 *         name: search
 *         schema:
 *           type: string
 *         description: 搜索关键词
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *         description: 状态筛选
 *       - in: query
 *         name: userId
 *         schema:
 *           type: string
 *         description: 用户ID筛选
 *       - in: query
 *         name: category
 *         schema:
 *           type: string
 *         description: 类别筛选
 *     responses:
 *       200:
 *         description: 成功返回设备列表
 */
router.get('/devices', async (req, res) => {
    try {
        const options = {
            page: parseInt(req.query.page) || 1,
            pageSize: parseInt(req.query.pageSize) || 10,
            search: req.query.search || '',
            status: req.query.status || '',
            userId: req.query.userId || '',
            category: req.query.category || ''
        };
        
        const result = await DeviceService.getDevices(options);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/devices/bind:
 *   post:
 *     tags:
 *     - device
 *     summary: 绑定设备
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               userId:
 *                 type: string
 *               deviceCode:
 *                 type: string
 *               deviceName:
 *                 type: string
 *               deviceModel:
 *                 type: string
 *               location:
 *                 type: string
 *               remark:
 *                 type: string
 *       required: true
 *     responses:
 *       201:
 *         description: 绑定成功
 *       400:
 *         description: 绑定失败
 */
router.post('/devices/bind', async (req, res) => {
    try {
        const bindData = req.body;
        const result = await DeviceService.bindDevice(bindData);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/devices/scan-bind:
 *   post:
 *     tags:
 *     - device
 *     summary: 扫码绑定设备
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               userId:
 *                 type: string
 *               qrCode:
 *                 type: string
 *       required: true
 *     responses:
 *       201:
 *         description: 绑定成功
 *       400:
 *         description: 绑定失败
 */
router.post('/devices/scan-bind', async (req, res) => {
    try {
        const scanData = req.body;
        const result = await DeviceService.scanBindDevice(scanData);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/devices/{id}/unbind:
 *   post:
 *     tags:
 *     - device
 *     summary: 解绑设备
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 设备ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               userId:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 解绑成功
 *       400:
 *         description: 解绑失败
 */
router.post('/devices/:id/unbind', async (req, res) => {
    try {
        const deviceId = req.params.id;
        const { userId } = req.body;
        const result = await DeviceService.unbindDevice(deviceId, userId);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/devices/repair:
 *   post:
 *     tags:
 *     - device
 *     summary: 提交设备报修
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               deviceId:
 *                 type: string
 *               userId:
 *                 type: string
 *               problem:
 *                 type: string
 *               priority:
 *                 type: string
 *               images:
 *                 type: array
 *                 items:
 *                   type: string
 *               contact:
 *                 type: string
 *       required: true
 *     responses:
 *       201:
 *         description: 报修成功
 *       400:
 *         description: 报修失败
 */
router.post('/devices/repair', async (req, res) => {
    try {
        const repairData = req.body;
        const result = await DeviceService.submitRepair(repairData);
        res.status(201).json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/devices/repairs:
 *   get:
 *     tags:
 *     - device
 *     summary: 获取报修记录
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: 页码
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *         description: 每页数量
 *       - in: query
 *         name: userId
 *         schema:
 *           type: string
 *         description: 用户ID筛选
 *       - in: query
 *         name: deviceId
 *         schema:
 *           type: string
 *         description: 设备ID筛选
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *         description: 状态筛选
 *     responses:
 *       200:
 *         description: 成功返回报修记录
 */
router.get('/devices/repairs', async (req, res) => {
    try {
        const options = {
            page: parseInt(req.query.page) || 1,
            pageSize: parseInt(req.query.pageSize) || 10,
            userId: req.query.userId || '',
            deviceId: req.query.deviceId || '',
            status: req.query.status || ''
        };
        
        const result = await DeviceService.getRepairRecords(options);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/devices/repairs/{id}/handle:
 *   post:
 *     tags:
 *     - device
 *     summary: 处理报修
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 报修ID
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               handlerId:
 *                 type: string
 *               action:
 *                 type: string
 *                 enum: [processing, completed, cancelled]
 *               note:
 *                 type: string
 *               solution:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 处理成功
 *       400:
 *         description: 处理失败
 */
router.post('/devices/repairs/:id/handle', checkTeacherOrAdmin, async (req, res) => {
    try {
        const repairId = req.params.id;
        const handleData = req.body;
        const result = await DeviceService.handleRepair(repairId, handleData);
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/devices/stats:
 *   get:
 *     tags:
 *     - device
 *     summary: 获取设备统计
 *     responses:
 *       200:
 *         description: 统计数据
 */
router.get('/devices/stats', checkTeacherOrAdmin, async (req, res) => {
    try {
        const result = await DeviceService.getDeviceStats();
        res.json(result);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/devices/logs:
 *   get:
 *     tags:
 *     - device
 *     summary: 获取设备操作日志
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *         description: 页码
 *       - in: query
 *         name: pageSize
 *         schema:
 *           type: integer
 *         description: 每页数量
 *       - in: query
 *         name: deviceId
 *         schema:
 *           type: string
 *         description: 设备ID筛选
 *       - in: query
 *         name: userId
 *         schema:
 *           type: string
 *         description: 用户ID筛选
 *       - in: query
 *         name: action
 *         schema:
 *           type: string
 *         description: 操作类型筛选
 *     responses:
 *       200:
 *         description: 成功返回操作日志
 */
router.get('/devices/logs', checkTeacherOrAdmin, async (req, res) => {
    try {
        const options = {
            page: parseInt(req.query.page) || 1,
            pageSize: parseInt(req.query.pageSize) || 10,
            deviceId: req.query.deviceId || '',
            userId: req.query.userId || '',
            action: req.query.action || ''
        };
        
        const result = await DeviceService.getDeviceLogs(options);
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

/**
 * @openapi
 * /api/v2/cabinets_stats:
 *   get:
 *     tags:
 *     - cabinet
 *     summary: 获取物料柜统计数据
 *     responses:
 *       200:
 *         description: 成功返回物料柜统计数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 data:
 *                   type: object
 *                   properties:
 *                     total:
 *                       type: integer
 *                       description: 物料柜总数
 *                     active:
 *                       type: integer
 *                       description: 在线设备数
 *                     offline:
 *                       type: integer
 *                       description: 离线设备数
 *                     cellStats:
 *                       type: object
 *                       properties:
 *                         totalCells:
 *                           type: integer
 *                           description: 总格子数
 *                         occupiedCells:
 *                           type: integer
 *                           description: 已占用格子数
 *                         occupancyRate:
 *                           type: number
 *                           description: 格子使用率
 *       500:
 *         description: 服务器错误
 */
router.get('/cabinets_stats', checkTeacherOrAdmin, async (req, res) => {
    try {
        const result = await CabinetEnhanced.getCabinetStats();
        res.json(result);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

module.exports = router;
